<?php

namespace app\common\model;
use think\facade\Db;
use think\facade\Env;
use utils\Tree;

class AreaModel extends BaseModel {

    protected $table = 'area';
    protected $pk    = 'code';

    /**
     * 创建static/system/plugins/jquery-citys/data.json
     */
    public function createJqueryCitys() {
        $list = $this->order('code asc')->column('name', 'code');
        file_put_contents('static/system/plugins/jquery-citys/data.json', json_encode($list, JSON_UNESCAPED_UNICODE));
    }

    public function createPickerCity(){
        $list = $this->field('code as id,f_code as pid,name')->order('code asc')->select()->toArray();
        $tree = Tree::channelLevel($list,0,'children');
        foreach($tree as $k1=>$v1){
            unset($v1['pid'],$v1['_level'],$v1['_html']);
            $tree[$k1] = $v1;
            $v1Children = $v1['children'];
            foreach($v1Children as $k2=>$v2){
                unset($v2['pid'],$v2['_level'],$v2['_html']);
                $tree[$k1]['children'][$k2] = $v2;
                $v2Children = $v2['children'] ?? [];
                foreach($v2Children as $k3=>$v3){
                    unset($v3['pid'],$v3['_level'],$v3['_html']);
                    $tree[$k1]['children'][$k2]['children'][$k3] = $v3;
                }
            }
        }
        $json = json_encode($tree,JSON_UNESCAPED_UNICODE);
        $content = <<<EOT
module.exports = $json;
EOT;
        file_put_contents('../mini/utils/picker.city.js', $content);
    }

    /**
     * 编码转化省市区
     * @param $code
     * @return string
     */
    public function getAreaName($code) {
        if(!cache('?area_full_name_list')){
            $list = $this->order('code asc')->column('full_name','code');
            cache('area_full_name_list',$list);
        }
        $list =  cache('area_full_name_list');
        return ($list[$code]);
    }


    /**
     * 获取省市区搜索条件
     * @param $code
     * @param string $field
     * @return array
     */
    public function getQuery($code, $field = 'area_code') {
        $provCode = $code - $code % 1e4;
        $cityCode = $code - ($code % 1e4 ? $code % 1e2 : $code);
        $distCode = $code % 1e2 ? $code : 0;
        if ($distCode > 0) return [$field, '=', $code];
        if ($cityCode > 0) return [$field, 'like', $code / 1e2 . '%'];
        if ($provCode > 0) return [$field, 'like', $code / 1e4 . '%'];;
        return [];
    }
    //地区接口
    static function areaList(){


        $region = DB::name('area')->field('code as id,f_code as pid,name')->order('code asc')->select()->toArray();
        foreach ($region as &$val) {
            $val['children'] = $val['pid'];
            unset($val['parent_id']);
        }
        $region_info = getVueTree($region, 0);
        return $region_info;
    }


}